#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "thread_pool.h"

void example_task(void *arg) {
    int num = *(int *)arg;
    printf("Processing task %d in thread %ld\n", num, pthread_self());
    free(arg); // 释放动态分配的任务参数
    sleep(1);  // 模拟任务耗时
}

int main() {
    printf("Initializing thread pool...\n");

    // 创建线程池，4 个线程，任务队列容量为 10
    ThreadPool *pool = thread_pool_create(4, 10);
    if (!pool) {
        fprintf(stderr, "Failed to create thread pool\n");
        return 1;
    }

    printf("Submitting tasks to the thread pool...\n");

    // 提交 20 个任务到线程池
    for (int i = 0; i < 20; i++) {
        int *arg = malloc(sizeof(int));
        if (!arg) {
            fprintf(stderr, "Failed to allocate memory for task argument\n");
            break;
        }
        *arg = i;
        if (thread_pool_add_task(pool, example_task, arg) != 0) {
            fprintf(stderr, "Failed to add task %d\n", i);
            free(arg); // 任务提交失败时释放参数
        }
    }

    printf("Waiting for tasks to complete...\n");

    // 等待一段时间，确保所有任务被执行
    sleep(10);

    printf("Destroying thread pool...\n");

    // 销毁线程池
    thread_pool_destroy(pool);

    printf("Thread pool destroyed. Exiting program.\n");

    return 0;
}
